import paddle
"""
Experimental modules
"""
import numpy as np
from models.common import Conv
from utils.downloads import attempt_download


class CrossConv(paddle.nn.Layer):

    def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
        super().__init__()
        c_ = int(c2 * e)
        self.cv1 = Conv(c1, c_, (1, k), (1, s))
        self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
        self.add = shortcut and c1 == c2

    def forward(self, x):
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))


class Sum(paddle.nn.Layer):

    def __init__(self, n, weight=False):
        super().__init__()
        self.weight = weight
        self.iter = range(n - 1)
        if weight:
            self.w = paddle.base.framework.EagerParamBase.from_tensor(tensor
                =-paddle.arange(start=1.0, end=n) / 2, trainable=True)

    def forward(self, x):
        y = x[0]
        if self.weight:
            w = paddle.nn.functional.sigmoid(x=self.w) * 2
            for i in self.iter:
                y = y + x[i + 1] * w[i]
        else:
            for i in self.iter:
                y = y + x[i + 1]
        return y


class MixConv2d(paddle.nn.Layer):

    def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
        super().__init__()
        groups = len(k)
        if equal_ch:
            i = paddle.linspace(start=0, stop=groups - 1e-06, num=c2).floor()
            c_ = [(i == g).sum() for g in range(groups)]
        else:
            b = [c2] + [0] * groups
            a = np.eye(groups + 1, groups, k=-1)
            a -= np.roll(a, 1, axis=1)
            a *= np.array(k) ** 2
            a[0] = 1
            c_ = np.linalg.lstsq(a, b, rcond=None)[0].round()
        self.m = paddle.nn.LayerList(sublayers=[paddle.nn.Conv2D(
            in_channels=c1, out_channels=int(c_[g]), kernel_size=k[g],
            stride=s, padding=k[g] // 2, bias_attr=False) for g in range(
            groups)])
        self.bn = paddle.nn.BatchNorm2D(num_features=c2)
        self.act = paddle.nn.LeakyReLU(negative_slope=0.1)

    def forward(self, x):
        return x + self.act(self.bn(paddle.concat(x=[m(x) for m in self.m],
            axis=1)))


class Ensemble(paddle.nn.LayerList):

    def __init__(self):
        super().__init__()

    def forward(self, x, augment=False, profile=False, visualize=False):
        y = []
        for module in self:
            y.append(module(x, augment, profile, visualize)[0])
        y = paddle.concat(x=y, axis=1)
        return y, None


def attempt_load(weights, map_location=None, inplace=True, fuse=True):
    from models.yolo import Detect, Model
    model = Ensemble()
    for w in (weights if isinstance(weights, list) else [weights]):
        ckpt = paddle.load(path=str(attempt_download(w)))
        if fuse:
            model.append(ckpt['ema' if ckpt.get('ema') else 'model'].astype
                (dtype='float32').fuse().eval())
        else:
            model.append(ckpt['ema' if ckpt.get('ema') else 'model'].astype
                (dtype='float32').eval())
    for m in model.sublayers():
        if type(m) in [paddle.nn.Hardswish, paddle.nn.LeakyReLU, paddle.nn.
            ReLU, paddle.nn.ReLU6, paddle.nn.Silu, Detect, Model]:
            m.inplace = inplace
            if type(m) is Detect:
                if not isinstance(m.anchor_grid, list):
                    delattr(m, 'anchor_grid')
                    setattr(m, 'anchor_grid', [paddle.zeros(shape=[1])] * m.nl)
        elif type(m) is Conv:
            m._non_persistent_buffers_set = set()
    if len(model) == 1:
        return model[-1]
    else:
        print(f'Ensemble created with {weights}\n')
        for k in ['names']:
            setattr(model, k, getattr(model[-1], k))
        model.stride = model[paddle.argmax(x=paddle.to_tensor(data=[m.
            stride.max() for m in model])).astype(dtype='int32')].stride
        return model
